using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Services.Identity.Domain;
using Services.Identity.Infrastructure;
using Services.Identity.WebApi.Request.User;
using Services.Identity.WebApi.Responses;
using Services.Initial.PublicProject.PublicClass.ExtensionException;
using Services.Initial.PublicProject.PublicClass.OutPutModels;
using Services.Initial.PublicProject.PublicMethods;

namespace Services.Identity.WebApi.Controllers;
[ApiController]
[Route("[controller]/[action]")]
public class UserManagerController(IDomainService domainService, MyIdentityDbContext dbContext) : ControllerBase
{
    private readonly IDomainService domainService = domainService;
    private readonly MyIdentityDbContext dbContext = dbContext;

    [HttpPost]
    public async Task<OutputModel<string>> AddUserToRole(string userName, string roleName)
    {
        var result = await domainService.AddUserToRoleAsync(userName, roleName);
        return OutPutMethod<string>.Success("操作成功");
    }
    [HttpPost]
    public async Task<OutputModel<string>> AddUser(AddUserRequest req)
    {
        var result = await this.domainService.AddUserAsync(req.UserName, req.UserPhone, req.Password);
        return OutPutMethod<string>.Success("操作成功");
    }
    [HttpPost]
    public async Task<OutputModel<string>> CreateVolunteerUser(AddUserRequest request)
    {
        await this.domainService.AddUserAsync(request.UserName, request.UserPhone, request.Password);
        await this.domainService.AddUserToRoleAsync(request.UserName, "Volunteer");
        var (_, token) = await this.domainService.LoginByUserPhoneAsync(request.UserPhone, request.Password);
        return OutPutMethod<string>.Success(token, message: "注册志愿者成功");
    }
    [HttpPost]
    public async Task<OutputModel<string>> CreateOrganizerUser(AddUserRequest request)
    {
        await this.domainService.AddUserAsync(request.UserName, request.UserPhone, request.Password);
        await this.domainService.AddUserToRoleAsync(request.UserName, "Organizer");
        var (_, token) = await this.domainService.LoginByUserPhoneAsync(request.UserPhone, request.Password);
        return OutPutMethod<string>.Success(token, message: "注册组织者成功");
    }
    [HttpDelete]
    public async Task<OutputModel<string>> DeleteUser(string userName)
    {
        var result = await this.domainService.DeleteUserAsync(userName);
        return OutPutMethod<string>.Success("操作成功");
    }
    [HttpGet]
    [Authorize]
    public async Task<OutputModel<UserInfoResponse>> GetUserInfo()
    {
        var id = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
        var user = await this.domainService.GetUserInfoByIdAsync(id);
        var roleName = await this.domainService.GetRoleByUserIdAsync(user);
        return OutPutMethod<UserInfoResponse>.Success(data: new UserInfoResponse(user.UserName!, roleName), errType: 0);
    }
    [HttpPost]
    [Authorize(Roles = "Admin")]
    public async Task<OutputModel<GetUserInformationByIdsResponse>> GetUserInformationByIds(GetUserInformationByIdsRequest req)
    {
        var users = new GetUserInformationByIdsResponse();
        foreach (var item in req.Ids!)
        {
            var user = await this.domainService.GetUserInfoByIdAsync(item) ?? throw new ExceptionWithStatus(System.Net.HttpStatusCode.NotFound, "不能输入无效的用户索引");
            users.Value.Add((item, user.UserName!));
        }
        return OutPutMethod<GetUserInformationByIdsResponse>.Success(users);
    }
    [HttpPost]
    [Authorize(Roles = "Admin")]
    public async Task<OutputModel<GetUserInformationByIdsResponse>> GetUserInformationByNames(GetUserInformationByNamesRequest req)
    {
        var users = new GetUserInformationByIdsResponse();
        foreach (var item in req.Names!)
        {
            var user = await this.domainService.GetUserInfoByNameAsync(item) ?? throw new ExceptionWithStatus(System.Net.HttpStatusCode.NotFound, "不能输入无效的用户索引");
            foreach (var useritem in user)
            {
                users.Value.Add((useritem.Id.ToString(), item));
            }
        }
        return OutPutMethod<GetUserInformationByIdsResponse>.Success(users);
    }
    [HttpGet]
    [Authorize]
    public async Task<OutputModel<int>> GetUserMessageCount()
    {
        var id = Convert.ToInt64(this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value);
        var resultCount = await this.dbContext.Messages.AsNoTracking().Include(x => x.UnsentUsers).Where(x => x.UnsentUsers.Any(x => x.UserId == id)).CountAsync();
        return OutPutMethod<int>.Success(resultCount);
    }
    [HttpGet]
    [Authorize]
    public async Task<OutputModel<List<GetActivityAllMessageResponse>>> GetActivityAllMessage([FromQuery] GetActivityAllMessageRequest request)
    {
        var list = await this.dbContext.Messages.AsNoTracking().Where(x => x.ActivityId == request.ActivityId).ToListAsync();
        var result = list.Select(x => new GetActivityAllMessageResponse(x.ActivityId, x.CreateTime, x.Message, x.MessageId)).ToList();
        return OutPutMethod<List<GetActivityAllMessageResponse>>.Success(result, 1, "刷新成功");
    }

}